package com.wswy.wyjk.ui.practice

import android.arch.lifecycle.Observer
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.PagerSnapHelper
import android.support.v7.widget.RecyclerView
import android.widget.RelativeLayout
import com.my.httpapi.api.baseUtils.LogUtils
import com.raft.framework.base.RFBaseActivity
import com.wswy.wyjk.R
import com.wswy.wyjk.model.PracticeType
import com.wswy.wyjk.model.vo.ExamRegularConfig
import com.wswy.wyjk.ui.EXTRA_DATA
import com.wswy.wyjk.ui.common.Router
import com.wswy.wyjk.ui.practice.dialog.ExamRegularHintDialog
import com.wswy.wyjk.ui.practice.dialog.ExamSubmitDialog
import com.wswy.wyjk.ui.practice.interface1.PracticeToOnline
import com.wswy.wyjk.utils.ToastUtils
import com.wswy.wyjk.utils.gone
import com.wswy.wyjk.utils.visible
import kotlinx.android.synthetic.main.activity_practice.*
import kotlinx.android.synthetic.main.layout_exam_btns.*

/**
 * 题目练习
 */
class PracticeActivity : RFBaseActivity() {

    private lateinit var practiceViewModel: PracticeViewModel
    private lateinit var practiceAdapter: PracticeAdapter

    private lateinit var examViewModel: ExamViewModel
    private lateinit var practiceController: PracticeController


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_practice)

        practiceViewModel = provideViewModel(PracticeViewModel::class.java)
        practiceController = PracticeController(this)

        val manager = LinearLayoutManager(this)
        manager.orientation = LinearLayoutManager.HORIZONTAL
        recyclerView.layoutManager = manager

        recyclerView.setItemViewCacheSize(0)

        practiceAdapter = PracticeAdapter(practiceViewModel, PracticeToOnline {
            practiceController.request(it)
        })
        recyclerView.adapter = practiceAdapter


        val snapHelper = PagerSnapHelper()
        snapHelper.attachToRecyclerView(recyclerView)


//        //上一题
//        tv_prev_practice.setOnClickListener {
//
//            offsetPractice(practiceViewModel.uiData.currentPosition, -1)
//        }
//
//        //下一题
//        tv_next_practice.setOnClickListener {
//
//            offsetPractice(practiceViewModel.uiData.currentPosition, 1)
//        }

        tv_order_index.setOnClickListener {
            showRecord()
        }

        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                //滑动后更新题目序号
                snapHelper.findSnapView(manager)?.run {
                    val pos = recyclerView.getChildAdapterPosition(this)
                    if (pos != -1) {
                        onScrollChange(pos)
                    }
                }

            }

        })

        //获取当前练习题目
        practiceViewModel.getPracticeLiveData().observe(this, Observer {

            it?.run {

                practiceViewModel.uiData.count = size

                practiceAdapter.setNewData(this)
                practiceAdapter.notifyDataSetChanged()

                //恢复到上次练习的位置
                val lastPosition = practiceViewModel.getLastPosition()
                if (lastPosition < size) {
                    practiceViewModel.uiData.currentPosition = lastPosition

                    recyclerView.scrollToPosition(lastPosition)
                }
                updatePosition()

                updateRecordCount()

            }
        })

        //答题记录弹窗隐藏
        practiceViewModel.getRecordSelectedLiveData().observe(this, Observer {
            it?.run {

                //换到指定位置
                practiceViewModel.uiData.currentPosition = this
                recyclerView.scrollToPosition(this)
                updatePosition()

            }
        })

        //点击了题目，做题反馈
        practiceViewModel.getCurrPracticeLiveData().observe(this, Observer {

            it?.run {

                //                val old = practiceAdapter.getItemData(uiData.currentPosition)
//                Timber.e("old  ${old.recordData}")
//
//                Timber.e("curr  ${recordData}")

                //如果答题正确 自动下一个
                if (isRight()) {

                    //非考试模式自动下一题
                    if (practiceViewModel.isExamMode()) {
                        practiceAdapter.notifyItemChanged(practiceViewModel.uiData.currentPosition)
                    } else {
                        recyclerView.postDelayed({
                            offsetPractice(practiceViewModel.uiData.currentPosition, 1)
                        }, 100)
                    }

                } else {
                    practiceAdapter.notifyItemChanged(practiceViewModel.uiData.currentPosition)

                }

                updateRecordCount()

                if (practiceViewModel.isExamMode() && practiceViewModel.getUndoneCount() == 0) {
                    //考试做完了
                    endExam()
                }

            }

        })


        intent?.getParcelableExtra<PracticeType?>(EXTRA_DATA)?.run {

            //当前做题类型
            practiceViewModel.practiceType = this


            when (type) {
                PracticeType.TYPE_ORDER -> {
                    tv_t.text = getString(R.string.order_test)
                }
                PracticeType.TYPE_CHAPTER -> {
                    tv_t.text = getString(R.string.chapter_list_page_title)
                }
                PracticeType.TYPE_RANDOM -> {
                    tv_t.text = getString(R.string.random_test)
                }
                PracticeType.TYPE_DIFFICULTY -> {
                    tv_t.text = getString(R.string.difficulty_test)
                }
                PracticeType.TYPE_UNDONE -> {
                    tv_t.text = getString(R.string.undone_test)
                }
                PracticeType.TYPE_ERROR -> {
                    tv_t.text = getString(R.string.err_test)
                }
                PracticeType.TYPE_EXAM -> {
                    tv_t.text = getString(R.string.mock_exam)

                    changeExamUi()
                    initExam()
                }

                PracticeType.TYPE_EXAM_WRONG_LIST -> {
                    tv_t.text = getString(R.string.mock_exam)
                    //背题模式
                    ll_practice_mode.gone()
                }

            }

        } ?: kotlin.run {
            finish()
        }
        initViews()
    }

    private fun initViews() {
        img_back.setOnClickListener {
            finish()
        }

        //却换练习模式
        ll_practice_mode2.chooserCallback = {

            when (it) {
                0 -> {
                    //答题
                    practiceViewModel.uiData.uiModel = UIPracticeData.MODEL_EXERCISE

                    practiceAdapter.notifyDataSetChanged()
                }
                1 -> {
                    //背题
                    practiceViewModel.uiData.uiModel = UIPracticeData.MODEL_EXPLAIN

                    practiceAdapter.notifyDataSetChanged()
                }
            }
        }

    }

    //更新对错数
    private fun updateRecordCount() {
        tv_right_count.text = practiceViewModel.uiData.rightCount.toString()
        tv_wrong_count.text = practiceViewModel.uiData.wrongCount.toString()
    }

    /**
     * 显示答题记录弹窗
     */
    private fun showRecord() {

        RecordDialog.newInstance().showNow(supportFragmentManager, "record")

    }

    private fun offsetPractice(position: Int, offset: Int) {
        //上一题  下一题却换
        if ((offset < 0 && practiceViewModel.uiData.currentPosition > 0 && position > 0) || (offset > 0 && position != -1 && position < practiceAdapter.itemCount)) {

            recyclerView.smoothScrollToPosition(position + offset)
            practiceViewModel.uiData.currentPosition += offset
            updatePosition()

        }
    }

    private fun onScrollChange(position: Int) {

        practiceViewModel.uiData.currentPosition = position

        updatePosition()

    }

    private fun updatePosition() {
        tv_order_index.text =
            "${practiceViewModel.uiData.currentPosition + 1}/${practiceViewModel.uiData.count}"
    }

    override fun onStop() {
        super.onStop()
        practiceViewModel.saveSession(practiceViewModel.uiData.currentPosition)
    }

    override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)

        if (this::practiceViewModel.isInitialized) {
            practiceViewModel.saveSession(practiceViewModel.uiData.currentPosition)
        }
    }

    private fun changeExamUi() {
        //隐藏答题背题模式切换
        ll_practice_mode.gone()
//        tv_prev_practice.gone()
//        tv_next_practice.gone()

        (tv_order_index.layoutParams as? RelativeLayout.LayoutParams)?.let {
            it.removeRule(RelativeLayout.CENTER_HORIZONTAL)

            tv_order_index.layoutParams = it
        }

        fl_exam_btns.visible()

        //考试状态
        ll_exam_status.setOnClickListener {

            examViewModel.toggleExamStatus()

        }
        //立即交卷
        tv_immed_submit.setOnClickListener {

            //
            val undoneCount = practiceViewModel.getUndoneCount()
            if (undoneCount > 0) {
                ExamSubmitDialog(this, undoneCount) {
                    endExam()
                }.show()
            } else {
                endExam()
            }


        }


    }

    private fun initExam() {
        examViewModel = provideViewModel(ExamViewModel::class.java)

        examViewModel.getCountTimeLiveData().observe(this, Observer {

            it?.let {
                tv_countdown_time.text = it
            }

        })

        examViewModel.getExamStatusLiveData().observe(this, Observer {
            it?.let {
                if (it) {
                    img_exam_status.setImageResource(R.drawable.exam_stop)
                } else {
                    img_exam_status.setImageResource(R.drawable.exam_replay)
                }
            }
        })

        practiceViewModel.practiceType?.let {
            examViewModel.findExamConfig(it)?.let {

                examViewModel.examRegularConfig = it

                showExamRegularDialog(it)
            }
        }

    }

    private fun showExamRegularDialog(config: ExamRegularConfig) {
        ExamRegularHintDialog(this, config).also {

            it.setOnDismissListener {
                examViewModel.startExam()
            }

        }.show()
    }

    private fun endExam() {

        examViewModel.endExam()

        Router.start(this, Router.EXAM_RESULT)

        finish()
    }

}